package net.threeple.logger.data.enhancer;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.google.common.base.CaseFormat;

import net.threeple.logger.data.annotation.Changer;
import net.threeple.logger.data.annotation.Recordable;
import net.threeple.logger.data.annotation.Recorder;
import net.threeple.logger.data.exception.NoEnoughInformationException;
import net.threeple.logger.data.model.DataLog;

public abstract class RecorderAbstractAspect {
	static final Logger logger = LoggerFactory.getLogger(RecorderAbstractAspect.class);
	
	@After("@annotation(recorder)")
	public void record(JoinPoint joinPoint, Recorder recorder) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod(); 
		Class<?>[] paramTypes = method.getParameterTypes();
		Annotation[][] parameterAnnotations = method.getParameterAnnotations();
		if(parameterAnnotations.length < 2) {
			throw new NoEnoughInformationException("没有足够的信息可供记录数据变更");
		}
		Object[] args = joinPoint.getArgs();
		int i = 0;
		
		DataLog log = new DataLog();
		log.setChangeTime(new Date());
		String methodName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, method.getName());
		String operationType = methodName.toUpperCase();
		if(methodName.indexOf("_") > 0) {
			operationType = methodName.substring(0, methodName.indexOf("_"));
		}
		log.setOperationType(operationType);
		
		for(Annotation[] annotations : parameterAnnotations) {
			Class<?> paramType = paramTypes[i];
			Object arg = args[i];
			i++;
			for(Annotation annotation : annotations) {
				if(annotation instanceof Recordable) {// 数据实体
					Recordable recordable = (Recordable) annotation;
					BeanWrapper data = new BeanWrapperImpl(arg);
					String payloadId = String.valueOf(data.getPropertyValue(recordable.id()));
					log.setPayloadId(payloadId);
					log.setPayloadClazz(paramType.getName());
					log.setPayload(arg);
				}
				if(annotation instanceof Changer) {// 操作用户
					Changer changer = (Changer)annotation;
					BeanWrapper user = new BeanWrapperImpl(arg);
					String userId = String.valueOf(user.getPropertyValue(changer.id()));
					log.setUserId(userId);
					log.setUserClazz(paramType.getName());
				}
			}
		}
		saveLog(log);
	}
	
	public abstract boolean saveLog(DataLog log);
}
